<template>
  <px-scrollbar v-show="!isMain && isView" class="view-equip-detail">
    <px-button style="margin: 16px 0 24px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
    <div class="page-tabs-group">
      <div v-for="item in pageTabs" :key="item.id" class="page-tab" :class="activeTab === item.id ? 'active' : ''" @click="tabClick(item.id)">
        {{ item.label }}
      </div>
    </div>
    <div v-show="activeTab === '0'">
      <div class="view-equip-title">物资信息</div>
      <div class="view-equip-wrap">
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">物资类型</div>
            <div class="text">{{ formValue.typeName }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">物资名称</div>
            <div class="text">{{ formValue.name }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">物资编码</div>
            <div class="text">{{ formValue.code }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">规格型号</div>
            <div class="text">{{ formValue.specification }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">品牌</div>
            <div class="text">{{ formValue.brand }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">单位</div>
            <div class="text">{{ formValue.unit }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">库存总数</div>
            <div class="text">{{ formValue.currentStock }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">安全库存</div>
            <div class="text">{{ formValue.safeStock }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">库存状态</div>
            <div class="text">
              <div v-if="formValue.warningStatus === '1'" class="tag" style="color: #10b981; background: #e8f8f3; border: 1px solid #b7ead9">
                {{ formValue.warningStatusValue }}
              </div>
              <div v-else-if="formValue.warningStatus === '2'" class="tag" style="color: #ef4444; background: #feecec; border: 1px solid #fac7c7">
                {{ formValue.warningStatusValue }}
              </div>
            </div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">设备二维码</div>
            <div class="text">
              <px-upload v-model:file-list="qrcodeList" :limit="1" list-type="picture-card">
                <template #file="{ file }">
                  <div>
                    <img class="px-upload-list__item-thumbnail" :src="file.url || file.fileUrl" alt="" />
                    <span class="px-upload-list__item-actions">
                      <!-- {{ file }} -->
                      <span @click="photoPreview">
                        <px-icon><zoom-in /></px-icon>
                      </span>
                      <span @click="photoDownload(file)">
                        <px-icon>
                          <Download />
                        </px-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </px-upload>
              <px-dialog v-model="dialogVisiblePlus">
                <img w-full :src="qrcodeUrl" style="margin: 0 auto" alt="设备二维码" />
              </px-dialog>
            </div>
          </div>
          <div class="view-equip-item large">
            <div class="label">物资标签</div>
            <div v-if="qrcodeImg[0]" class="text">
              <PhotoUpload photoType="view" :photoData="{ moduleName: 'eqpFile' }" :photoList="qrcodeImg" />
            </div>
            <div v-else class="text">-</div>
          </div>
        </div>
      </div>
      <div class="view-equip-title">库存详情</div>
      <px-table :data="facDTOListData" class="equip-table" size="small" height="calc(72vh - 311px)" border>
        <px-table-column label="序号" min-width="60" align="center" fixed="left">
          <template #default="{ $index }"> {{ $index + 1 }} </template>
        </px-table-column>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <span v-if="item.warningStatusValue">
              <px-tag
                v-if="item.warningStatusValue"
                effect="plain"
                :style="{
                  cursor: 'pointer',
                  color: `${tagColorList[scope.row.warningStatus]}`,
                  border: `1px solid ${tagBorderColorList[scope.row.warningStatus]}`,
                  backgroundColor: `${tagBgColorList[scope.row.warningStatus]}`
                }"
              >
                {{ scope.row.warningStatusValue }}
              </px-tag>
              <span v-else> {{ scope.row.eqpStatusValue || "-" }} </span>
            </span>
            <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
          </template>
        </px-table-column>
      </px-table>
    </div>
    <div v-show="activeTab === '1'">
      <px-table :data="warehousingTableData" class="equip-table" size="small" height="calc(100vh - 280px)" border>
        <px-table-column type="index" label="序号" width="64" show-overflow-tooltip fixed="left" />
        <px-table-column fixed="left" prop="inNum" label="入库单号" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <px-button type="primary" link size="small" @click="toInNum(scope.row)">{{ scope.row.inNum }}</px-button>
          </template>
        </px-table-column>
        <px-table-column prop="inDate" label="入库时间" min-width="120" show-overflow-tooltip />
        <px-table-column prop="storeLocation" label="存放地块" min-width="120" show-overflow-tooltip />
        <px-table-column prop="quantity" label="入库数量" min-width="80" show-overflow-tooltip />
        <px-table-column prop="inUserName" label="操作人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="approveName" label="审批人" min-width="120" show-overflow-tooltip />
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="formValue.pageNum"
        v-model:limit="formValue.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <div v-show="activeTab === '2'">
      <px-table :data="outboundTableData" class="equip-table" size="small" height="calc(100vh - 280px)" border>
        <px-table-column type="index" label="序号" width="64" show-overflow-tooltip fixed="left" />
        <px-table-column fixed="left" prop="outNum" label="出库单号" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <px-button type="primary" link size="small" @click="toOutNum(scope.row)">{{ scope.row.outNum }}</px-button>
          </template>
        </px-table-column>
        <px-table-column prop="outDate" label="出库时间" min-width="120" show-overflow-tooltip />
        <px-table-column prop="quantity" label="出库数量" min-width="120" show-overflow-tooltip />
        <px-table-column prop="outUserName" label="操作人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="approveName" label="审批人" min-width="120" show-overflow-tooltip />
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="formValue.pageNum"
        v-model:limit="formValue.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable1"
      />
    </div>
  </px-scrollbar>
</template>
<script setup lang="ts">
import { reactive, toRefs, watch, computed, getCurrentInstance, ref } from "vue";
import { queryByMaterialCode, queryByMaterialCodeListIn, queryByMaterialCodeListOut } from "@/api/erc/material";
import { useRouter, useRoute } from "vue-router";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { dataURLtoBlob } from "@/utils/common";
const router = useRouter();
const route = useRoute();

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "sparePartsId", "code", "rowData"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
const qrcodeList = ref([]);
const dialogVisiblePlus = ref(false);
const qrcodeUrl = ref("");
const qrcodeImg = ref([]); // 设备二维码文件
// 页面本身的值
const { proxy }: any = getCurrentInstance();
const state = reactive<any>({
  pageTabs: [
    { id: "0", label: "物资信息" },
    { id: "1", label: "物资入库" },
    { id: "2", label: "物资出库" }
  ],
  activeTab: "0", // 默认在备件信息tab
  formValue: {},
  formValueTable: {
    pageNum: 1,
    pageSize: 20
  },
  facDTOListData: [],
  warehousingTableData: [],
  outboundTableData: [],
  id: "",
  total: 0,
  tableColumns: [
    { prop: "storeLocation", label: "存放地块", minWidth: "510", showOverflowTooltip: true, fixed: "left" },
    { prop: "facCount", label: "当前数量", minWidth: "510", showOverflowTooltip: true },
    { prop: "warningStatusValue", label: "库存状态", minWidth: "510", showOverflowTooltip: true, warningStatusValue: true }
  ]
});
const { pageTabs, activeTab, formValue, formValueTable, tableColumns, facDTOListData, warehousingTableData, outboundTableData, total } =
  toRefs(state);
const tagColorList = {
  1: "#10B981", // 正常
  2: "#EF4444" // 预警
};
const tagBorderColorList = {
  1: "#B7EAD9", // 正常
  2: "#FAC7C7" // 预警
};
const tagBgColorList = {
  1: "#E8F8F3", // 正常
  2: "#FEECEC" // 预警
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && props.isView) {
    activeTab.value = "0";
    tabClick("0");
    getUrl();
    const { bigFileDTO } = props.rowData;
    qrcodeImg.value = [bigFileDTO];
  } else {
    formValueTable.value = {
      pageNum: 1,
      pageSize: 20
    };
  }
});
const photoPreview = () => {
  dialogVisiblePlus.value = true;
};
// 点击tab显示页面详情
const tabClick = async id => {
  activeTab.value = id;
  if (id === "0") {
    const data: any = await queryByMaterialCode({ code: props.code });
    formValue.value = data;
    facDTOListData.value = data?.facDTOList;
  } else if (id === "1") {
    queryTable();
  } else if (id === "2") {
    queryTable1();
  }
};
//下载文件
const photoDownload = file => {
  const link = document.createElement("a");
  link.style.display = "none";
  link.href = file.url;
  link.setAttribute("download", file.name);
  document.body.appendChild(link);
  link.click();

  document.body.removeChild(link);
};
const getUrl = async () => {
  axios({
    method: "post",
    url: "/ifp/erc/api/v1/material/createQrCode",
    // data: { materialCode: props.rowData.code },
    data: { materialCode: props.code },
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + (getToken().accessToken || "")
    }
  }).then(async res => {
    const blob = dataURLtoBlob(res.data);
    const imgSrc = URL.createObjectURL(blob);
    qrcodeUrl.value = imgSrc; // 图片下载地址
    qrcodeList.value = [];
    qrcodeList.value.push({ url: res.data, name: "设备二维码" }); // 图片展示地址
  });
};

//物资入库详情
const queryTable = async () => {
  const params = {
    materialCode: props.code ? props.code : props.sparePartsId,
    pageNum: formValueTable.value.pageNum,
    pageSize: formValueTable.value.pageSize
  };
  const data: any = await queryByMaterialCodeListIn(params);
  total.value = data?.total;
  warehousingTableData.value = data?.data;
};
//物资出库详情
const queryTable1 = async () => {
  const params = {
    materialCode: props.code ? props.code : props.sparePartsId,
    pageNum: formValueTable.value.pageNum,
    pageSize: formValueTable.value.pageSize
  };
  const data: any = await queryByMaterialCodeListOut(params);
  total.value = data?.total;
  outboundTableData.value = data?.data;
};
// 返回主页面
const backMainPage = () => {
  emits("backMainPage");
};
// 跳转到入库单号详情页面
const toInNum = row => {
  router.push({ path: "/erc/material/in", query: { id: row.inNum } });
};

// 跳转到出库单号详情页面
const toOutNum = row => {
  router.push({ path: "/erc/material/out", query: { id: row.outNum } });
};
</script>
<style lang="scss" scoped>
@import url("@/views/erc/scss/view-detail.scss");

:deep(.px-upload--picture-card) {
  display: none;
}
</style>
